package com.zuo.seckilldemo.handler;

import com.zuo.seckilldemo.entity.User;
import com.zuo.seckilldemo.service.UserService;
import com.zuo.seckilldemo.utils.CookieUtils;
import com.zuo.seckilldemo.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) return true;
        String userToken = CookieUtils.getCookieValue(request, "userToken", true);
        if (userToken ==null){
            return false;
        }
        User user = userService.getByToken(userToken, request, response);
        if (user ==null) return false;
        UserThreadLocal.set(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)  {
        UserThreadLocal.remove();
    }
}
